package cn.zhengzhou.springbootmybatis.utils;


import cn.zhengzhou.springbootmybatis.pojo.User;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.SimpleFormatter;

@Slf4j
@Service
public class JwtUtil {
    /**
     * 密码
     */
    @Value("${jwt.secret}")
    private String secret;
    /**
     * 过期时间
     */
    @Value("${jwt.expiration}")
    private int expiration;

    /***
     * 获取token
     * @param user
     * @return
     */
    public String createToken(User user) {
        log.info("用户Id是{}", user.getId());
        String token = JWT
                .create()
                .withAudience(String.valueOf(user.getId())) //将user id 保存到token 作为载荷
                .withExpiresAt(new Date(System.currentTimeMillis()+expiration * 1000))//1 小时后过期
                .withClaim("userId", String.valueOf(user.getId()))
                .withClaim("username", user.getUsername())
                .withClaim("timestamp", String.valueOf(System.currentTimeMillis()))
                .sign(Algorithm.HMAC256(secret));

        return token;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public Boolean verifyToken(String token) {
        if (token == null||token.isEmpty()) {
            return false;
        }
        //使用静态方法就无法注入secret
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        System.out.println(verify);
        return true;


    }
}
